/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#ifndef XERN_PACKET_HPP
#define XERN_PACKET_HPP

#include <boost/array.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <vector>

#include "Message.hpp"

namespace XernMetaverse
{
	using namespace Xern;
    namespace posix_time = boost::posix_time;

    class Packet
    {
    public:
        static const int FL_ZERO_CODE = 0x80; // Is zero encoded?.
        static const int FL_RELIABLE = 0x40; // Is waiting and acknowledge?.
        static const int FL_RESENT = 0x20; // Is a resend from the source?.
        static const int FL_ACKS = 0x10; // Is this packet containing acknowledges?.

        //static const int MAX_PACKET_SIZE = 1240; // Minimum IPv6 MTU.
        static const int MAX_PACKET_SIZE = (1<<16) - 40; // Minimum IPv6 MTU.
        static const int MAX_PACKET_HEADER = 10; // Not counting extra header.

        Packet();
        ~Packet();

        void Decode(const MessageTemplates &templates);
        void Encode();

        typedef boost::array<char, MAX_PACKET_SIZE> BufferType;
        BufferType buffer;
        unsigned int packetSize;

        // Packet header.
        u8 flags;
        u32 sequenceNumber;

        // Packet payload.
        boost::shared_ptr<Message> message;
        std::vector<unsigned int> acks;

        // Packet control data.
        posix_time::ptime firstSendTime;
        posix_time::ptime lastSendTime;
        int sendCount;

        void *operator new(size_t numbytes);
        void operator delete(void *pointer);
    };

}; // namespace Xern

#endif //XERN_PACKET_HPP
